package verifycode

import (
	"time"

	"github.com/runningwater/gohub/pkg/app"
	"github.com/runningwater/gohub/pkg/config"
	"github.com/runningwater/gohub/pkg/redis"
)

// RedisStore 实现了 verifycode.Store 接口
// 验证码存储在 Redis 中
// 键名格式为：keyPrefix:code
type RedisStore struct {
	RedisClient *redis.Client
	KeyPrefix   string
}

// 保存验证码
func (s *RedisStore) Set(key string, value string) bool {
	expirTime := time.Minute * time.Duration(config.GetInt64("verifycode.expire_time"))
	// 本地环境方便调试
	if app.IsLocal() {
		expirTime = time.Minute * time.Duration(config.GetInt64("verifycode.debug_expire_time"))
	}
	// 生成 Redis 键名
	redisKey := s.KeyPrefix + key
	// 设置 Redis 键值
	return s.RedisClient.Set(redisKey, value, expirTime)
}

// 获取验证码
func (s *RedisStore) Get(key string, clear bool) string {
	key = s.KeyPrefix + key
	val := s.RedisClient.Get(key)
	if clear {
		s.RedisClient.Del(key)
	}
	return val
}

// 检查验证码是否正确
func (s *RedisStore) Verify(key, answer string, clear bool) bool {
	v := s.Get(key, clear)
	return v == answer
}

func NewRedisStore() *RedisStore {
	return &RedisStore{
		RedisClient: redis.Redis,
		KeyPrefix:   config.GetString("app.name") + ":verifycode:",
	}

}
